package com.partner.boot.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelWriter;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletOutputStream;
import java.net.URLEncoder;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.partner.boot.common.Constants;
import com.partner.boot.common.annotation.AutoLog;
import com.partner.boot.entity.*;
import com.partner.boot.mapper.MessagesMapper;
import com.partner.boot.service.IUserService;
import com.partner.boot.utils.SessionUtils;
import com.partner.boot.utils.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.io.InputStream;
import java.util.List;
import java.util.Objects;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.partner.boot.common.Result;
import org.springframework.web.multipart.MultipartFile;
import com.partner.boot.service.IApplyService;

import org.springframework.web.bind.annotation.RestController;

/**
* <p>
*  前端控制器
* </p>
*
* @author 小熊
* @since 2023-03-23
*/
@RestController
@RequestMapping("/apply")
@Slf4j
public class ApplyController {

    @Resource
    private IApplyService applyService;

    @Resource
    IUserService userService;

    @PostMapping
    @SaCheckPermission("apply.add")
    @AutoLog("发送好友申请")
    public Result save(@RequestBody User user) {
        // 当前用户信息
        User dbUser = (User) StpUtil.getSession().get(Constants.LOGIN_USER_KEY);
        // 申请者id
        Integer id = user.getId();

        Apply apply = new Apply();
        apply.setUid(dbUser.getId());
        apply.setTid(id);

        //  消息提示
        String content = dbUser.getUsername() +  " 向你发出 添加好友申请 " ;

        MessagesMapper messagesMapper = SpringContextUtil.getBean(MessagesMapper.class);
        Messages messages = new Messages();
        messages.setContent(content);
        messages.setUserId(id);
        messages.setTime(DateUtil.now());
        messagesMapper.insert(messages);

        applyService.save(apply);
        return Result.success();
    }

    @PutMapping
    @SaCheckPermission("apply.edit")
    @AutoLog("编辑好友申请")
    public Result update(@RequestBody Apply apply) {
        applyService.updateById(apply);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    @SaCheckPermission("apply.delete")
    @AutoLog("删除好友申请")
    public Result delete(@PathVariable Integer id) {
        applyService.removeById(id);
        return Result.success();
    }

    @PostMapping("/del/batch")
    @SaCheckPermission("apply.deleteBatch")
    @AutoLog("批量删除好友申请")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        applyService.removeByIds(ids);
        return Result.success();
    }

    @GetMapping
    @SaCheckPermission("apply.list")
    public Result findAll() {
        return Result.success(applyService.list());
    }

    // 获取当前用户的好友申请情况
    @GetMapping("/hot")
    @SaCheckPermission("apply.list")
    public Result hot(@RequestParam Integer pageNum,
                      @RequestParam Integer pageSize) {
        QueryWrapper<Apply> queryWrapper = new QueryWrapper<Apply>().orderByDesc("id");
        Page<Apply> page = applyService.page(new Page<>(pageNum, pageSize), queryWrapper);

        List<User> users = userService.list();
        // 当前用户
        User dbuser = (User) StpUtil.getSession().get(Constants.LOGIN_USER_KEY);

        int count = 0;
        int j=0;
        // log.info("page.getTotal: "+page.getTotal()+" ");
        for(int i = 0;i<page.getTotal();i++){
            //log.info("前：申请表里的Tid: "+page.getRecords().get(i).getTid() + "；---- i: "+ i + "；---- j: " + j + " ；---- 当前用户 uid：" + dbuser.getId()+"；----  count "+count+"；----  count+j "+(count+j) );
            if(!Objects.equals(page.getRecords().get(i).getTid(), dbuser.getId())){
                page.getRecords().remove(page.getRecords().get(i));
                i--;
                count++;
            }else {
                j++;
            }

            if (count+j == page.getTotal()){
                break;
            }
        }

        // 根据fid添加好友的user对象
        for (Apply record : page.getRecords()) {
            users.stream().filter(user -> user.getId().equals(record.getUid())).findAny().ifPresent(record::setUser);
        }

        return Result.success(page);
    }


    @GetMapping("/{id}")
    @SaCheckPermission("apply.list")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(applyService.getById(id));
    }

    @GetMapping("/page")
    @SaCheckPermission("apply.list")
    public Result findPage(@RequestParam(defaultValue = "") String name,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        QueryWrapper<Apply> queryWrapper = new QueryWrapper<Apply>().orderByDesc("id");
        queryWrapper.like(!"".equals(name), "name", name);

        User currentUser = SessionUtils.getUser();
        String role = currentUser.getRole();
        if ("USER".equals(role)) {  // 用户
            queryWrapper.eq("tid", currentUser.getId());  // select * from  dynamic where user_id = xxx
        }

        return Result.success(applyService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }


    /**
    * 导出接口
    */
    @GetMapping("/export")
    @SaCheckPermission("apply.export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<Apply> list = applyService.list();
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("Apply信息表", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();

    }

    /**
    * excel 导入
    * @param file
    * @throws Exception
    */
    @PostMapping("/import")
    @SaCheckPermission("apply.import")
    public Result imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        // 通过 javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟javabean的属性要对应起来
        List<Apply> list = reader.readAll(Apply.class);

        applyService.saveBatch(list);
        return Result.success();
    }

}
